package stone926.mods.more_enchantments.items.bow;

import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.mob.MobEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.projectile.ExplosiveProjectileEntity;
import net.minecraft.item.BowItem;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import stone926.mods.more_enchantments.MoreEnchantmentsMod;
import stone926.mods.more_enchantments.enchantments.RandomFireballShooterEnchantment;

import java.util.function.Predicate;

public class RandomFireballBow extends BowItem implements StoneBow {

  public RandomFireballBow(Settings settings) {
    super(settings);
  }

  @Override
  public void onStoppedUsing(ItemStack bowStack, World world, LivingEntity user, int remainingUseTicks) {
    if (user instanceof PlayerEntity playerEntity) {
      boolean isCreative = playerEntity.getAbilities().creativeMode;
      ItemStack arrowStack = playerEntity.getArrowType(bowStack);
      if (!arrowStack.isEmpty() || isCreative) {
        if (arrowStack.isEmpty()) {arrowStack = new ItemStack(MoreEnchantmentsMod.MIXED_GUNPOWDER);}
        int useTime = this.getMaxUseTime(bowStack) - remainingUseTicks;
        int lvl = EnchantmentHelper.getLevel(MoreEnchantmentsMod.RANDOM_FIREBALL_SHOOTER, bowStack);
        float pullProgress = BowItem.getPullProgress(useTime);
        if (pullProgress >= 0.3) {
          ExplosiveProjectileEntity fireball = RandomFireballShooterEnchantment.getFireball(lvl, user, world, pullProgress, EnchantmentHelper.getLevel(MoreEnchantmentsMod.FLASH, bowStack));
          if (world.spawnEntity(fireball)) {
            int infiniteLvl = EnchantmentHelper.getLevel(MoreEnchantmentsMod.INFINITE, bowStack);
            if (infiniteLvl <= 2 && !isCreative) {
              arrowStack.decrement(1);
              if (arrowStack.isEmpty()) {playerEntity.getInventory().removeOne(arrowStack);}
            }
            bowStack.damage(user.getRandom().nextDouble() > pullProgress ? 4 : 2, playerEntity, p -> p.sendToolBreakStatus(playerEntity.getActiveHand()));
            if (user.getRandom().nextDouble() / 2 > pullProgress) {user.damage(DamageSource.MAGIC, lvl + 2);}
          }
        }
      }
    }
  }

  @Override
  public Predicate<ItemStack> getProjectiles() {
    return stack -> stack.isOf(MoreEnchantmentsMod.MIXED_GUNPOWDER);
  }

  @Override
  public void mobUse(MobEntity user, LivingEntity target, ItemStack stack, float pullProgress, ItemStack usingStack) {
    World world = user.getEntityWorld();
    int lvl = EnchantmentHelper.getLevel(MoreEnchantmentsMod.RANDOM_FIREBALL_SHOOTER, usingStack);
    ExplosiveProjectileEntity fireball = RandomFireballShooterEnchantment.getFireball(lvl, user, world, 1, EnchantmentHelper.getLevel(MoreEnchantmentsMod.FLASH, stack));
    world.spawnEntity(fireball);
  }

}
